#include "table.h"
#include <cstring>
#include <cstdio>

tdf_name_table::tdf_name_table(){}
tdf_name_table::~tdf_name_table(){}

void tdf_name_table::clear(){
    nameTable.clear();
}

unsigned int tdf_name_table::addName(sLabel* lbl){
    unsigned int ctr = 0;
    for(vector<sLabel>::iterator i = nameTable.begin(); i < nameTable.end(); i++ ){
        if( *i == *lbl ){
            return ctr;
        }
        ctr++;
    }
    nameTable.push_back(sLabel(lbl));
    return ctr;
}
unsigned int tdf_name_table::addName(string* str){
    sLabel lbl( str );
    return addName( &lbl );
}
unsigned int tdf_name_table::addName(char* str){
    sLabel lbl( str );
    return addName( &lbl );
}

bool tdf_name_table::findName(sLabel* lbl,unsigned int* out){
    unsigned int ctr = 0;
    for(vector<sLabel>::iterator i = nameTable.begin(); i < nameTable.end(); i++ ){
        if( *i == *lbl ){
            *out = ctr;
            return true;
        }
        ctr++;
    }
    return false;
}
bool tdf_name_table::findName(string* str,unsigned int* out){
    sLabel lbl( str );
    return findName( &lbl, out );
}
bool tdf_name_table::findName(char* str,unsigned int* out){
    sLabel lbl( str );
    return findName( &lbl, out );
}

string tdf_name_table::getName(unsigned int index){
    return nameTable.at(index).strVal;
}
unsigned int tdf_name_table::getNumName(){
    return nameTable.size();
}

void tdf_name_table::exportNameTable(FILE* outfile){

    unsigned int size = nameTable.size();
    fwrite(&size,sizeof(unsigned int),1,outfile);

    for( vector<sLabel>::iterator i = nameTable.begin(); i < nameTable.end(); i++ ){
        unsigned short stack = strlen( (*i).strVal.c_str() );
        fwrite( &stack , sizeof( unsigned short ), 1 , outfile );
        fwrite( (*i).strVal.c_str(), stack, 1, outfile );
    }

    fflush(outfile);

}

void tdf_name_table::importNameTable(FILE* infile){

    nameTable.clear();

    unsigned int size;
    char* buffer;
    fread( &size, sizeof( unsigned int ), 1, infile );

    for(unsigned int i = 0; i < size; i++ ){
        unsigned short len;
        fread( &len, sizeof( unsigned short), 1, infile );
        buffer = new char[len+1];
        fread( buffer, len, 1, infile );
        buffer[len] = 0x00;
        nameTable.push_back( sLabel(buffer) );
        delete[] buffer;
    }

}

tdf_content_table::tdf_content_table(): uptodate(true){}
tdf_content_table::~tdf_content_table(){}

void tdf_content_table::markModified(){
    uptodate = false;
}
